package pub.wkq.auth.mq;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;
import pub.wkq.auth.service.MqLocalMsgRecordService;
import pub.wkq.pojo.MqLocalMsgRecord;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * MQ 消息处理处理器
 */
@Component
public class InitResumeMQProducerHandler {
    @Resource
    private MqLocalMsgRecordService mqLocalMsgRecordService;
    /**
     * 存储本地消息记录列表
     */
    private ThreadLocal<List<String>> msgIdsThreadLocal = new ThreadLocal<>();

    /**
     * 保存本地消息记录
     *
     * @param exchangeName 交换机名称
     * @param routingKey   路由键
     * @param msgContent   消息内容
     */
    public void saveLocalMsgRecord(String exchangeName, String routingKey, String msgContent) {
        MqLocalMsgRecord mqLocalMsgRecord = new MqLocalMsgRecord();
        mqLocalMsgRecord.setTargetExchange(exchangeName);
        mqLocalMsgRecord.setRoutingKey(routingKey);
        mqLocalMsgRecord.setMsg(msgContent);
        mqLocalMsgRecord.setCreateTime(LocalDateTime.now());
        mqLocalMsgRecord.setUpdateTime(LocalDateTime.now());
        mqLocalMsgRecordService.save(mqLocalMsgRecord);
        // 将消息记录的id存入本地线程变量
        //从 threadLocal 中获取本地消息 Ids,如果为空则初始化.
        List<String> msgIds = msgIdsThreadLocal.get();
        if (msgIds == null) {
            msgIds = Lists.newArrayList();
        }
        //每次消息存储在本地表中之后,都需要存储在当前线程中,事务提交以后可以对其进行检查
        msgIds.add(mqLocalMsgRecord.getId());
        msgIdsThreadLocal.set(msgIds);
    }
}